import 'package:simulator/core/result.dart';
import 'package:simulator/utils/constant.dart';
import 'package:simulator/utils/rx_util.dart';
import 'package:win32/win32.dart';

///寄存器
class Regisiter {
  final int addr;
  int _value;
  final int def;
  final String label;
  final String description;
  final bool isGeneral;

  Regisiter(
      {required this.addr,
      this.label = '',
      this.description = '',
      this.def = 0,
      this.isGeneral = false})
      : _value = def & 0xff;

  int get value => _value;
  set value(int value) {
    //assert(value >= 0 && value <= 0xff, 'regisiter value must 0-0xFF');
    int old = _value;
    _value = value & 0xff;

    ///通知各个模块寄存器变化了开始处理,外部各个模块监听地址上的数据变化
    Rx.getInstance()
        .push(signRegisiter, data: RegisiterUpdate(addr, old, _value));
  }

  set valueNot(int value) {
    _value = value & 0xff;
  }

  void reset() => _value = def;

  int mask(int mask) => _value & mask;

  void setBit(int mask) => _value |= mask;

  void clearBit(int mask) => _value &= ~mask;

  ///相同为0，不同为1
  ///任何二进制数与零异或，都会等于其本身
  void filpBit(int mask) => _value ^= mask;

  bool isOdd() {
    int count = 0;
    int condition = _value;
    while (condition > 0) {
      if (condition % 2 == 1) count++;
      condition = condition ~/ 2;
    }
    return count.isOdd;
  }

  @override
  String toString() {
    return '$label :[${addr.toHexString(8)}:${_value.toHexString(8)}]';
  }
}
